package com.shlh.saas.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shlh.saas.entity.User;
import com.shlh.saas.entity.UserBalance;
import com.shlh.saas.mapper.UserMapper;
import com.shlh.saas.mapper.UserBalanceMapper;
import com.shlh.saas.service.UserService;
import com.shlh.saas.common.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 用户服务实现类
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserBalanceMapper userBalanceMapper;

    public UserServiceImpl(UserBalanceMapper userBalanceMapper) {
        this.userBalanceMapper = userBalanceMapper;
        log.info("UserServiceImpl被创建，Bean名称为: userService");
    }

    @Override
    public User findByUsername(String username) {
        log.debug("查询用户名为 {} 的用户", username);
        return getBaseMapper().findByUsername(username);
    }

    @Override
    public User findByPhone(String phone) {
        log.debug("查询手机号为 {} 的用户", phone);
        return getBaseMapper().findByPhone(phone);
    }

    @Override
    @Transactional
    public boolean register(User user) {
        log.info("开始注册用户: {}", user.getUsername());

        // 检查用户名、手机号是否已存在
        if (findByUsername(user.getUsername()) != null) {
            log.warn("用户名 {} 已存在", user.getUsername());
            throw new RuntimeException("用户名已存在");
        }
        if (user.getPhone() != null && findByPhone(user.getPhone()) != null) {
            log.warn("手机号 {} 已存在", user.getPhone());
            throw new RuntimeException("手机号已存在");
        }

        // 设置默认值
        user.setIsFirstLogin(1);
        user.setIsDeleted(0);

        boolean result = getBaseMapper().insert(user) > 0;

        if (result) {
            log.info("用户 {} 注册成功，ID: {}", user.getUsername(), user.getId());
            
            // 为新用户创建默认余额记录
            try {
                UserBalance userBalance = new UserBalance();
                userBalance.setUserId(user.getId());
                userBalance.setPhone(user.getPhone());
                userBalance.setVipLevel(0); // 默认免费版
                userBalance.setCashBalance(new BigDecimal("0.00"));
                userBalance.setExportQuotaRemaining(0);
                userBalance.setViewRecordsRemaining(5); // 默认可查看5页
                userBalance.setReverseLookupRemaining(0);
                userBalance.setEmailSendRemaining(0);
                userBalance.setCreatedAt(LocalDateTime.now());
                userBalance.setUpdatedAt(LocalDateTime.now());
                
                userBalanceMapper.insert(userBalance);
                log.info("为新用户 {} 创建余额记录成功", user.getUsername());
            } catch (Exception e) {
                log.error("为新用户 {} 创建余额记录失败: {}", user.getUsername(), e.getMessage(), e);
                // 不影响用户注册的结果
            }
        } else {
            log.error("用户 {} 注册失败", user.getUsername());
        }

        return result;
    }

    @Override
    @Transactional
    public boolean updatePassword(Long userId, String newPassword) {
        User user = getById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        user.setIsFirstLogin(0);
        return updateById(user);
    }

    @Override
    @Transactional
    public boolean createUserByPhone(String phone) {
        // 检查手机号是否已存在
        User existingUser = findByPhone(phone);
        if (existingUser != null) {
            return true; // 用户已存在，直接返回
        }

        // 创建新用户
        User user = new User();
        user.setPhone(phone);
        // 生成随机用户名
        user.setUsername("user_" + UUID.randomUUID().toString().substring(0, 8));
        // 首次登录标记为true
        user.setIsFirstLogin(1);
        // 设置默认值
        user.setIsDeleted(0);

        // 使用userMapper.insert代替save
        boolean result = getBaseMapper().insert(user) > 0;

        if (result) {
            log.info("通过手机号创建用户成功: {}, ID: {}", phone, user.getId());
            
            // 为新用户创建默认余额记录
            try {
                UserBalance userBalance = new UserBalance();
                userBalance.setUserId(user.getId());
                userBalance.setPhone(user.getPhone());
                userBalance.setVipLevel(0); // 默认免费版
                userBalance.setCashBalance(new BigDecimal("0.00"));
                userBalance.setExportQuotaRemaining(0);
                userBalance.setViewRecordsRemaining(5); // 默认可查看5页
                userBalance.setReverseLookupRemaining(0);
                userBalance.setEmailSendRemaining(0);
                userBalance.setCreatedAt(LocalDateTime.now());
                userBalance.setUpdatedAt(LocalDateTime.now());
                
                userBalanceMapper.insert(userBalance);
                log.info("为新用户(手机号:{})创建余额记录成功", phone);
            } catch (Exception e) {
                log.error("为新用户(手机号:{})创建余额记录失败: {}", phone, e.getMessage(), e);
                // 不影响用户创建的结果
            }
        } else {
            log.error("通过手机号创建用户失败: {}", phone);
        }

        return result;
    }

    @Override
    public User getUserByPhone(String phone) {
        System.out.println("UserServiceImpl.getUserByPhone - 开始查询用户: " + phone);

        // 创建查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        queryWrapper.eq("is_deleted", 0); // 未删除的用户

        // 执行查询
        User user = getBaseMapper().selectOne(queryWrapper);
        System.out.println("UserServiceImpl.getUserByPhone - 查询结果: " + (user != null ? user.getUsername() : "null"));
        return user;
    }
    
    @Override
    public User getUserById(Long userId) {
        System.out.println("UserServiceImpl.getUserById - 开始查询用户: " + userId);
        User user = getBaseMapper().selectById(userId);
        System.out.println("UserServiceImpl.getUserById - 查询结果: " + (user != null ? user.getUsername() : "null"));
        return user;
    }

    @Override
    public boolean updateUser(User user) {
        System.out.println("UserServiceImpl.updateUser - 开始更新用户: " + user.getId());
        // 只更新允许修改的字段
        User updateUser = new User();
        updateUser.setId(user.getId());
        
        // 只有非空字段才更新
        if (user.getUsername() != null) {
            updateUser.setUsername(user.getUsername());
            System.out.println("将更新用户名: " + user.getUsername());
        }
        if (user.getPhone() != null) {
            updateUser.setPhone(user.getPhone());
            System.out.println("将更新手机号: " + user.getPhone());
        }
        
        int rows = getBaseMapper().updateUserById(updateUser);
        System.out.println("UserServiceImpl.updateUser - 更新结果: 影响行数=" + rows);
        return rows > 0;
    }

    @Override
    @Transactional
    public boolean buyExportQuota(Long userId, Integer amount, BigDecimal totalPrice) {
        log.info("开始购买导出次数: userId={}, amount={}, totalPrice={}", userId, amount, totalPrice);
        
        // 1. 获取用户信息
        User user = getBaseMapper().selectById(userId);
        if (user == null) {
            log.warn("用户不存在: userId={}", userId);
            return false;
        }
        
        try {
            // 2. 获取用户余额信息
            UserBalance userBalance = userBalanceMapper.selectByUserId(userId);
            
            if (userBalance == null) {
                log.warn("用户余额记录不存在，创建新记录: userId={}", userId);
                // 如果不存在则创建新记录
                userBalance = new UserBalance();
                userBalance.setUserId(userId);
                userBalance.setPhone(user.getPhone());
                userBalance.setVipLevel(0); // 默认免费版
                userBalance.setCashBalance(new BigDecimal("0.00"));
                userBalance.setExportQuotaRemaining(0);
                userBalance.setViewRecordsRemaining(5); // 默认可查看5页
                userBalance.setReverseLookupRemaining(0);
                userBalance.setEmailSendRemaining(0);
                userBalance.setCreatedAt(LocalDateTime.now());
                userBalance.setUpdatedAt(LocalDateTime.now());
                userBalanceMapper.insert(userBalance);
                
                // 重新查询以获取ID
                userBalance = userBalanceMapper.selectByUserId(userId);
                if (userBalance == null) {
                    log.error("创建用户余额记录失败: userId={}", userId);
                    return false;
                }
            }
            
            log.info("当前用户导出次数配额: {}", userBalance.getExportQuotaRemaining());
            
            // 3. 扣除账户余额
            BigDecimal currentCashBalance = userBalance.getCashBalance();
            if (currentCashBalance.compareTo(totalPrice) < 0) {
                log.warn("用户余额不足: userId={}, currentBalance={}, requiredAmount={}", 
                         userId, currentCashBalance, totalPrice);
                return false;
            }
            
            // 4. 增加导出次数配额并减少现金余额
            Integer newExportQuota = userBalance.getExportQuotaRemaining() + amount;
            BigDecimal newCashBalance = currentCashBalance.subtract(totalPrice);
            
            log.info("更新后的导出次数配额: {}, 更新后的现金余额: {}", newExportQuota, newCashBalance);
        
            // 5. 更新用户余额信息
            userBalance.setExportQuotaRemaining(newExportQuota);
            userBalance.setCashBalance(newCashBalance);
            userBalance.setUpdatedAt(LocalDateTime.now());
        
            int rows = userBalanceMapper.updateById(userBalance);
            log.info("购买导出次数更新结果: 影响行数={}", rows);
        
            // 6. 记录交易（可以在项目需要时添加）
        
        return rows > 0;
        } catch (Exception e) {
            log.error("购买导出次数过程中发生异常: {}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    @Transactional
    public boolean buySearchQuota(Long userId, Integer amount, BigDecimal totalPrice) {
        log.info("开始购买查看更多次数: userId={}, amount={}, totalPrice={}", userId, amount, totalPrice);
        
        // 1. 获取用户信息
        User user = getBaseMapper().selectById(userId);
        if (user == null) {
            log.warn("用户不存在: userId={}", userId);
            return false;
        }
        
        try {
            // 2. 获取用户余额信息
            UserBalance userBalance = userBalanceMapper.selectByUserId(userId);
            
            if (userBalance == null) {
                log.warn("用户余额记录不存在，创建新记录: userId={}", userId);
                // 如果不存在则创建新记录
                userBalance = new UserBalance();
                userBalance.setUserId(userId);
                userBalance.setPhone(user.getPhone());
                userBalance.setVipLevel(0); // 默认免费版
                userBalance.setCashBalance(new BigDecimal("0.00"));
                userBalance.setExportQuotaRemaining(0);
                userBalance.setViewRecordsRemaining(5); // 默认可查看5页
                userBalance.setReverseLookupRemaining(0);
                userBalance.setEmailSendRemaining(0);
                userBalance.setCreatedAt(LocalDateTime.now());
                userBalance.setUpdatedAt(LocalDateTime.now());
                userBalanceMapper.insert(userBalance);
                
                // 重新查询以获取ID
                userBalance = userBalanceMapper.selectByUserId(userId);
                if (userBalance == null) {
                    log.error("创建用户余额记录失败: userId={}", userId);
                    return false;
                }
            }
            
            log.info("当前用户可查看页数: {}", userBalance.getViewRecordsRemaining());
            
            // 3. 扣除账户余额
            BigDecimal currentCashBalance = userBalance.getCashBalance();
            if (currentCashBalance.compareTo(totalPrice) < 0) {
                log.warn("用户余额不足: userId={}, currentBalance={}, requiredAmount={}", 
                         userId, currentCashBalance, totalPrice);
                return false;
            }
            
            // 4. 增加查看页数配额并减少现金余额
            Integer newViewPagesQuota = userBalance.getViewRecordsRemaining() + amount;
            BigDecimal newCashBalance = currentCashBalance.subtract(totalPrice);
            
            log.info("更新后的查看页数配额: {}, 更新后的现金余额: {}", newViewPagesQuota, newCashBalance);
        
            // 5. 更新用户余额信息
            userBalance.setViewRecordsRemaining(newViewPagesQuota);
            userBalance.setCashBalance(newCashBalance);
            userBalance.setUpdatedAt(LocalDateTime.now());
        
            int rows = userBalanceMapper.updateById(userBalance);
            log.info("购买查看更多次数更新结果: 影响行数={}", rows);
        
            // 6. 记录交易（可以在项目需要时添加）
        
        return rows > 0;
        } catch (Exception e) {
            log.error("购买查看更多次数过程中发生异常: {}", e.getMessage(), e);
            return false;
        }
    }
} 